

#######################
### Install and Load Libraries
#######################

# Define packages to be used in the replication code
packages <- c("ggplot2", "psych", "ltm", "Rmisc", "tidyr", "broom", "stargazer",
              "patchwork", "mediation", "readr", "stringr", "weights", "dplyr")

# Install the packages that are not yet installed
install.packages(setdiff(packages, rownames(installed.packages())))

# Load all of the packages
lapply(packages, library, character.only = TRUE)

# Set a constant seed
set.seed(89)



#######################
#### Load and rename datasets 
#######################

# Make sure that the datafile is saved in the same directory as the project to enable easy loading. 

# Loading datasets
load("Metaverse_Dataset.RData")        

# Renaming datasets
Data <- Data_Metaverse


#######################
#### Figure 3 = Baseline Level of Support and Effect of Scandal on Support for Tech Regulation
#######################

# styling constants so both panels match (this will be used in later figures too) 
cap_len   <- 0.12   
err_lwd   <- 0.9    
pt_size   <- 3      

# Summarize baseline levels of support for regulating tech firms - divided by country
plot <- summarySE(Data, measurevar="tech_reg_score_factor_WaveA_4item", groupvars=c("Country"), na.rm=T)

# Create a lookup for full names
plot$Country <- factor(plot$Country,
                       levels = c("US", "UK", "DE", "FR"),
                       labels = c("United States", "United Kingdom", "Germany", "France"))

P1 <-
  ggplot(plot, aes(y = Country, x = tech_reg_score_factor_WaveA_4item)) + 
  geom_errorbar(
    aes(xmin = tech_reg_score_factor_WaveA_4item - ci,
        xmax = tech_reg_score_factor_WaveA_4item + ci),
    height = cap_len, linewidth = err_lwd, orientation = "y"
  ) +
  geom_point(size = pt_size) + 
  xlim(3.4, 4.2) +
  ylab("") + xlab("\nBaseline Support for Tech Regulation") +
  ggtitle("(a) Baseline Support for Tech \nRegulation - Wave 1") +
  theme_classic() +
  theme(plot.title = element_text(hjust = 0.5))


#A: Pooled Model
pooled_model <- lm(tech_reg_score_factor_WaveB_4item ~ Treatment_Group, data = Data)
pooled_tidy <- tidy(pooled_model, conf.int = TRUE, conf.level = 0.90) %>%
  filter(term == "Treatment_GroupTech - Scandal") %>%
  mutate(Country = "Pooled")

#B: Country Models
country_models <- Data %>%
  group_by(Country) %>%
  group_map(~ tidy(lm(tech_reg_score_factor_WaveB_4item ~ Treatment_Group, data = .x),
                   conf.int = TRUE, conf.level = 0.90) %>%
              filter(term == "Treatment_GroupTech - Scandal") %>%
              mutate(Country = unique(.x$Country)),
            .keep = TRUE) %>%
  bind_rows()

# Add pooled result to combined dataframe
all_coefs <- bind_rows(pooled_tidy, country_models)

# Relabel and order countries
country_labels <- c(
  "FR" = "France",
  "DE" = "Germany",
  "UK" = "United Kingdom",
  "US" = "United States",
  "Pooled" = "Pooled Countries"  
)

all_coefs$Country <- recode(all_coefs$Country, !!!country_labels)
all_coefs$Country <- factor(
  all_coefs$Country,
  levels = rev(c("Pooled Countries", "France", "Germany", "United Kingdom", "United States"))
)


# Plot
all_coefs <- all_coefs %>%
  mutate(color_flag = ifelse(Country == "Pooled Countries", "Pooled Countries", "Other"))

P2 <- 
  ggplot(all_coefs, aes(y = Country, x = estimate, color = color_flag)) +
  geom_point(size = pt_size) +
  geom_errorbar(
    aes(xmin = conf.low, xmax = conf.high),
    height = cap_len, linewidth = err_lwd,    orientation = "y"
  ) +
  geom_vline(xintercept = 0, linetype = "dashed") +
  xlab("\nScandal Treatment Effect") + ylab("") +
  xlim(-0.10, 0.7) +
  ggtitle("(b) Treatment Effects of Tech Scandal on \nRegulatory Preferences - Wave 2") +
  scale_color_manual(values = c("Pooled Countries" = "blue", "Other" = "black")) +
  theme_classic() +
  theme(
    plot.title = element_text(hjust = 0.5),
    axis.text.y = element_text(
      color = ifelse(levels(factor(all_coefs$Country)) == "Pooled Countries", "blue", "black")
    ),
    legend.position = "none"
  )


#Generate Combined Plot with Both Panels
P1 + P2




#######################
#### Figure 4: Political Orientation and the Effect of the Scandal Treatment on Tech Regulation, by Country
#######################

par(mfrow = c(2, 2), mar=c(4,4,3,1))
thermo_sim <- 0:10

# Analysis for US
mod1 <- lm(tech_reg_score_factor_WaveB_4item ~ Treatment_Group*lr, 
           data = subset(Data, Country == "US"))
summary(mod1)

treat <- coef(mod1)[2] + coef(mod1)[4] * thermo_sim
treat_se <- sqrt(vcov(mod1)[2, 2] + thermo_sim^2 * vcov(mod1)[4, 4] + 2 * thermo_sim * vcov(mod1)[2, 4])
plot(x = thermo_sim, y = treat, type = "p",pch=16,
     xlab = "Political Orientation",
     ylab = "Treatment Effect",
     main = "United States",
     ylim = c(-0.6,0.8), cex.lab=1.1)
for(i in 1:11){
  lines(c(i-1,i-1),c(treat[i],treat[i] + 1.96 * treat_se[i]),lwd=2)
  lines(c(i-1,i-1),c(treat[i],treat[i] - 1.96 * treat_se[i]),lwd=2)
}
abline(h=0,lty="dashed")


# Analysis for UK
mod2 <- lm(tech_reg_score_factor_WaveB_4item ~ Treatment_Group*lr, 
           data = subset(Data, Country == "UK"))
summary(mod2)

treat <- coef(mod2)[2] + coef(mod2)[4] * thermo_sim
treat_se <- sqrt(vcov(mod2)[2, 2] + thermo_sim^2 * vcov(mod2)[4, 4] + 2 * thermo_sim * vcov(mod2)[2, 4])
plot(x = thermo_sim, y = treat, type = "p",pch=16,
     xlab = "Political Orientation",
     ylab = "",
     main = "United Kingdom",
     ylim = c(-0.6,0.8), cex.lab=1.1)
for(i in 1:11){
  lines(c(i-1,i-1),c(treat[i],treat[i] + 1.96 * treat_se[i]),lwd=2)
  lines(c(i-1,i-1),c(treat[i],treat[i] - 1.96 * treat_se[i]),lwd=2)
}
abline(h=0,lty="dashed")


# Analysis for France
mod3 <- lm(tech_reg_score_factor_WaveB_4item ~ Treatment_Group*lr, 
           data = subset(Data, Country == "FR"))
summary(mod3)

treat <- coef(mod3)[2] + coef(mod3)[4] * thermo_sim
treat_se <- sqrt(vcov(mod3)[2, 2] + thermo_sim^2 * vcov(mod3)[4, 4] + 2 * thermo_sim * vcov(mod3)[2, 4])
plot(x = thermo_sim, y = treat, type = "p",pch=16,
     xlab = "Political Orientation",
     ylab = "Treatment Effect",
     main = "France",
     ylim = c(-0.6,0.8), cex.lab=1.1)
for(i in 1:11){
  lines(c(i-1,i-1),c(treat[i],treat[i] + 1.96 * treat_se[i]),lwd=2)
  lines(c(i-1,i-1),c(treat[i],treat[i] - 1.96 * treat_se[i]),lwd=2)
}
abline(h=0,lty="dashed")


# Analysis for Germany
mod4 <- lm(tech_reg_score_factor_WaveB_4item ~ Treatment_Group*lr, 
           data = subset(Data, Country == "DE"))
summary(mod4)

treat <- coef(mod4)[2] + coef(mod4)[4] * thermo_sim
treat_se <- sqrt(vcov(mod4)[2, 2] + thermo_sim^2 * vcov(mod4)[4, 4] + 2 * thermo_sim * vcov(mod4)[2, 4])
plot(x = thermo_sim, y = treat, type = "p",pch=16,
     xlab = "Political Orientation",
     ylab = "",
     main = "Germany",
     ylim = c(-0.6,0.8), cex.lab=1.1)
for(i in 1:11){
  lines(c(i-1,i-1),c(treat[i],treat[i] + 1.96 * treat_se[i]),lwd=2)
  lines(c(i-1,i-1),c(treat[i],treat[i] - 1.96 * treat_se[i]),lwd=2)
}
abline(h=0,lty="dashed")

par(mfrow = c(1, 1))




#######################
#### Figure 5: Baseline Salience and Effect of Scandal on Issue Salience of Tech Regulation
#######################

plot <- summarySE(Data, measurevar="salience_tech_WaveA", groupvars=c("Country"), na.rm=T)

# Create a lookup for full names
plot$Country <- factor(plot$Country,
                       levels = c("US", "UK", "DE", "FR"),
                       labels = c("United States", "United Kingdom", "Germany", "France"))

P3 <-
  ggplot(plot, aes(y = Country, x = salience_tech_WaveA)) + 
  geom_errorbar(
    aes(xmin = salience_tech_WaveA - ci,
        xmax = salience_tech_WaveA + ci),
    height = cap_len, linewidth = err_lwd,    orientation = "y"
  ) +
  geom_point(size = pt_size) + 
  xlim(2.7, 3.7) +
  ylab("") + xlab("\nBaseline Issue Salience") +
  ggtitle("(a) Baseline Salience of Tech \nRegulation - Wave 1") +
  theme_classic() +
  theme(plot.title = element_text(hjust = 0.5))


# Panel A: Pooled Model
pooled_model <- lm(salience_tech_WaveB ~ Treatment_Group, data = Data)
pooled_tidy <- tidy(pooled_model, conf.int = TRUE, conf.level = 0.90) %>%
  filter(term == "Treatment_GroupTech - Scandal") %>%
  mutate(Country = "Pooled")

# Panel B: Country Models
country_models <- Data %>%
  group_by(Country) %>%
  group_map(~ tidy(lm(salience_tech_WaveB ~ Treatment_Group, data = .x),
                   conf.int = TRUE, conf.level = 0.90) %>%
              filter(term == "Treatment_GroupTech - Scandal") %>%
              mutate(Country = unique(.x$Country)),
            .keep = TRUE) %>%
  bind_rows()

# Add pooled result to combined dataframe
all_coefs <- bind_rows(pooled_tidy, country_models)

# Relabel and order countries
country_labels <- c(
  "FR" = "France",
  "DE" = "Germany",
  "UK" = "United Kingdom",
  "US" = "United States",
  "Pooled" = "Pooled Countries"  # Preserve Pooled
)

all_coefs$Country <- recode(all_coefs$Country, !!!country_labels)
all_coefs$Country <- factor(
  all_coefs$Country,
  levels = rev(c("Pooled Countries", "France", "Germany", "United Kingdom", "United States"))
)


# Plot
all_coefs <- all_coefs %>%
  mutate(color_flag = ifelse(Country == "Pooled Countries", "Pooled Countries", "Other"))

P4 <- 
  ggplot(all_coefs, aes(y = Country, x = estimate, color = color_flag)) +
  geom_point(size = pt_size) +
  geom_errorbar(
    aes(xmin = conf.low, xmax = conf.high),
    height = cap_len, linewidth = err_lwd,     orientation = "y"
  ) +
  geom_vline(xintercept = 0, linetype = "dashed") +
  xlab("\nScandal Treatment Effect") + ylab("") +
  xlim(-0.10, 0.90) +
  ggtitle("(b) Treatment Effects of Tech Scandal on \nIssue Salience - Wave 2") +
  scale_color_manual(values = c("Pooled Countries" = "blue", "Other" = "black")) +
  theme_classic() +
  theme(
    plot.title = element_text(hjust = 0.5),
    axis.text.y = element_text(
      color = ifelse(levels(factor(all_coefs$Country)) == "Pooled Countries", "blue", "black")
    ),
    legend.position = "none"
  )

P3 + P4




#######################
#### Figure 6: Baseline Levels and Effect of Scandal Treatment on Political Participation
#######################

plot <- summarySE(Data, measurevar="part_tech_factor_WaveA", groupvars=c("Country"), na.rm=T)

# Create a lookup for full names
plot$Country <- factor(plot$Country,
                       levels = c("US", "UK", "DE", "FR"),
                       labels = c("United States", "United Kingdom", "Germany", "France"))

P5 <-
  ggplot(plot, aes(y = Country, x = part_tech_factor_WaveA)) + 
  geom_errorbar(
    aes(xmin = part_tech_factor_WaveA - ci,
        xmax = part_tech_factor_WaveA + ci),
    height = cap_len, linewidth = err_lwd,    orientation = "y"
  ) +
  geom_point(size = pt_size) + 
  xlim(2.0, 3.1) +
  ylab("") + xlab("\nBaseline Political Participation") +
  ggtitle("(a) Baseline Political Participation for \nTech Regulation - Wave 1") +
  theme_classic() +
  theme(plot.title = element_text(hjust = 0.5))


# Panel A: Pooled Model
pooled_model <- lm(part_tech_factor_WaveB ~ Treatment_Group, data = Data)
pooled_tidy <- tidy(pooled_model, conf.int = TRUE, conf.level = 0.90) %>%
  filter(term == "Treatment_GroupTech - Scandal") %>%
  mutate(Country = "Pooled")

# Panel B: Country Models
country_models <- Data %>%
  group_by(Country) %>%
  group_map(~ tidy(lm(part_tech_factor_WaveB ~ Treatment_Group, data = .x),
                   conf.int = TRUE, conf.level = 0.90) %>%
              filter(term == "Treatment_GroupTech - Scandal") %>%
              mutate(Country = unique(.x$Country)),
            .keep = TRUE) %>%
  bind_rows()

# Add pooled result to combined dataframe
all_coefs <- bind_rows(pooled_tidy, country_models)

# Relabel and order countries
country_labels <- c(
  "FR" = "France",
  "DE" = "Germany",
  "UK" = "United Kingdom",
  "US" = "United States",
  "Pooled" = "Pooled Countries"  # Preserve Pooled
)

all_coefs$Country <- recode(all_coefs$Country, !!!country_labels)
all_coefs$Country <- factor(
  all_coefs$Country,
  levels = rev(c("Pooled Countries", "France", "Germany", "United Kingdom", "United States"))
)

# Plot
all_coefs <- all_coefs %>%
  mutate(color_flag = ifelse(Country == "Pooled Countries", "Pooled Countries", "Other"))

P6 <- 
  ggplot(all_coefs, aes(y = Country, x = estimate, color = color_flag)) +
  geom_point(size = pt_size) +
  geom_errorbar(
    aes(xmin = conf.low, xmax = conf.high),
    height = cap_len, linewidth = err_lwd,    orientation = "y"
  ) +
  geom_vline(xintercept = 0, linetype = "dashed") +
  xlab("\nScandal Treatment Effect") + ylab("") +
  xlim(-0.30, 0.60) +
  ggtitle("(b) Treatment Effects of Tech Scandal on \nPolitical Participation - Wave 2") +
  scale_color_manual(values = c("Pooled Countries" = "blue", "Other" = "black")) +
  theme_classic() +
  theme(
    plot.title = element_text(hjust = 0.5),
    axis.text.y = element_text(
      color = ifelse(levels(factor(all_coefs$Country)) == "Pooled Countries", "blue", "black")
    ),
    legend.position = "none"
  )

P5 + P6





#######################
#### Figure 7: Shifts in Issue Salience and Political Participation in Treatment Group
#######################

### Code for SummarySEWithin2 Function

summarySE2 <- function (data = NULL, measurevar, groupvars = NULL, na.rm = TRUE, conf.interval = 0.95) {
  library(data.table)
  data <- data.table(data)
  
  length2 <- function(x, na.rm = FALSE) {
    if (na.rm) 
      sum(!is.na(x))
    else length(x)
  }
  
  datac <- data[, .(unlist(lapply(.SD, length2, na.rm = na.rm)), 
                    unlist(lapply(.SD, mean, na.rm = na.rm)),
                    unlist(lapply(.SD, sd, na.rm = na.rm))),
                by = groupvars, .SDcols = measurevar]
  names(datac) <- c(groupvars, "N", measurevar, "sd")
  setkeyv(datac, groupvars)
  
  datac[, se := unlist(sd) / sqrt(unlist(N))] #compute standard error
  
  ciMult <- qt(conf.interval / 2 + 0.5, unlist(datac$N) - 1)
  datac[, ci := se * ciMult]
  datac <- data.frame(datac)
  return(datac)
}

normDataWithin2 <- function (data = NULL, idvar, measurevar, betweenvars = NULL, 
                             na.rm = TRUE) {
  library(data.table); library(dplyr)
  data <- data.table(data)
  setkeyv(data, idvar)
  
  data.subjMean <- data[, .(unlist(lapply(.SD, mean, na.rm = na.rm))), by = idvar, .SDcols = measurevar]
  names(data.subjMean) <- c(idvar, 'subjMean')
  data <- merge(data, data.subjMean)
  setkeyv(data, c(idvar, betweenvars))
  
  measureNormedVar <- paste(measurevar, "Normed", sep = "")
  data <- data.frame(data)
  
  data[, measureNormedVar] <- data[, measurevar] - unlist(data[, "subjMean"]) + mean(data[, measurevar], na.rm = na.rm)
  return(data)
}

# create normed and un-normed versions
summarySEwithin2 <- function (data = NULL, measurevar, betweenvars = NULL, withinvars = NULL, 
                              idvar = NULL, na.rm = TRUE, conf.interval = 0.95) {
  
  # Ensure that the betweenvars and withinvars are factors
  factorvars <- sapply(data[, c(betweenvars, withinvars), drop = FALSE], 
                       FUN = is.factor)
  if (!all(factorvars)) {
    nonfactorvars <- names(factorvars)[!factorvars]
    message("Automatically converting the following non-factors to factors: ", 
            paste(nonfactorvars, collapse = ", "))
    data[nonfactorvars] <- lapply(data[nonfactorvars], factor)
  }
  
  # Get the means from the un-normed data
  datac <- summarySE2(data, measurevar, groupvars=c(betweenvars, withinvars),
                      na.rm=na.rm, conf.interval=conf.interval)
  
  # Drop all the unused columns (these will be calculated with normed data)
  datac$sd <- NULL
  datac$se <- NULL
  datac$ci <- NULL
  
  # Norm each subject's data
  ndata <- normDataWithin2(data, idvar, measurevar, betweenvars, na.rm)
  
  # This is the name of the new column
  measurevar_n <- paste(measurevar, "Normed", sep="")
  
  # Collapse the normed data - now we can treat between and within vars the same
  ndatac <- summarySE2(ndata, measurevar_n, groupvars=c(betweenvars, withinvars),
                       na.rm=na.rm, conf.interval=conf.interval)
  
  # Apply correction from Morey (2008) to the standard error and confidence interval
  #  Get the product of the number of conditions of within-S variables
  nWithinGroups    <- prod(vapply(ndatac[,withinvars, drop=FALSE], FUN= function(x) length(levels(x)),
                                  FUN.VALUE=numeric(1)))
  correctionFactor <- sqrt( nWithinGroups / (nWithinGroups-1) )
  
  # Apply the correction factor
  ndatac$sd <- unlist(ndatac$sd) * correctionFactor
  ndatac$se <- unlist(ndatac$se) * correctionFactor
  ndatac$ci <- unlist(ndatac$ci) * correctionFactor
  
  # Combine the un-normed means with the normed results
  merged <- merge(datac, ndatac)
  #merged[, 1] <- as.numeric(as.character(merged[, 1]))
  #merged <- merged[order(merged[, 1]), ]
  return(merged)
}



# Calculting the delta between intended political participation in survey waves A and B and for issue salience

Data$Delta_Tech_Salience <- Data$salience_tech_WaveB - Data$salience_tech_WaveA
Data$Delta_Tech_Participation <- Data$part_tech_avg_WaveB - Data$part_tech_avg_WaveA

Data$Delta_Tech_Salience_Change_Three <- ifelse(Data$Delta_Tech_Salience > 0, "Increased Salience", 
                                                 ifelse(Data$Delta_Tech_Salience < 0, "Decreased Salience", 
                                                        "No Change in Salience"))

### Plotting the Figure

pd <- position_dodge(0.1) 

Combo_within <- Data %>% 
  filter(Treatment_Group == "Tech - Scandal" & Delta_Tech_Participation > -5 & Delta_Tech_Salience > -5)  %>%
  select(part_tech_factor_WaveA, part_tech_factor_WaveB,
         everything()) 

long_format_data <-
  pivot_longer(Combo_within, part_tech_factor_WaveA:part_tech_factor_WaveB, 
               names_to = "Wave_AB", 
               values_to="Participation_Score")

dfwc <- summarySEwithin2(long_format_data, measurevar="Participation_Score", withinvars=c("Delta_Tech_Salience_Change_Three", "Wave_AB"),
                         idvar="Longitudinal_ID", na.rm=T, conf.interval=.95) 

ggplot(dfwc,
       aes(x = Wave_AB,
           y = Participation_Score,
           color = Delta_Tech_Salience_Change_Three,
           linetype = Delta_Tech_Salience_Change_Three,
           group = Delta_Tech_Salience_Change_Three)) +
  geom_errorbar(width=.2,
                aes(ymin = Participation_Score - ci,
                    ymax = Participation_Score + ci),
                position = pd) +
  geom_line(position = pd) +
  geom_point(shape = 21, size = 2, fill = "white", position = pd) +
  ylim(2.2, 2.9) +
  scale_x_discrete(name = "\nWaves",
                   labels = c("part_tech_factor_WaveA" = "Wave 1",
                              "part_tech_factor_WaveB" = "Wave 2")) +
  ylab("Intended Political Participation\n") + 
  scale_color_discrete(name = "Salience Group") +
  scale_linetype_discrete(name = "Salience Group") +  
  theme_classic()



#######################
#### Figure 8: Effect of Scandal on Anger
#######################

# Panel A: Pooled Model
pooled_model <- lm(Angry ~ Treatment_Group, data = Data)
pooled_tidy <- tidy(pooled_model, conf.int = TRUE, conf.level = 0.90) %>%
  filter(term == "Treatment_GroupTech - Scandal") %>%
  mutate(Country = "Pooled")

# Panel B: Country Models
country_models <- Data %>%
  group_by(Country) %>%
  group_map(~ tidy(lm(Angry ~ Treatment_Group, data = .x),
                   conf.int = TRUE, conf.level = 0.90) %>%
              filter(term == "Treatment_GroupTech - Scandal") %>%
              mutate(Country = unique(.x$Country)),
            .keep = TRUE) %>%
  bind_rows()

# Add pooled result to combined dataframe
all_coefs <- bind_rows(pooled_tidy, country_models)

# Relabel and order countries
country_labels <- c(
  "FR" = "France",
  "DE" = "Germany",
  "UK" = "United Kingdom",
  "US" = "United States",
  "Pooled" = "Pooled Countries"  # Preserve Pooled
)

all_coefs$Country <- recode(all_coefs$Country, !!!country_labels)
all_coefs$Country <- factor(
  all_coefs$Country,
  levels = rev(c("Pooled Countries", "France", "Germany", "United Kingdom", "United States"))
)


# Plot
all_coefs <- all_coefs %>%
  mutate(color_flag = ifelse(Country == "Pooled Countries", "Pooled Countries", "Other"))

ggplot(all_coefs, 
       aes(y = Country, x = estimate, color = color_flag)) +
  geom_point(size = 3) +
  geom_errorbar(aes(xmin = conf.low, xmax = conf.high), height = 0.15, orientation = "y") +
  geom_vline(xintercept = 0, linetype = "dashed", color = "black") +
  xlab("\nTreatment Effect") + ylab("") +
  xlim(-.10, 2.00) +
  scale_color_manual(values = c("Pooled Countries" = "blue", "Other" = "black")) +
  theme_classic() +
  theme(plot.title = element_text(hjust = 0.5),
        axis.text.y = element_text(color = ifelse(levels(factor(all_coefs$Country)) == "Pooled Countries", "blue", "black")),
        legend.position = "none") 




#######################
#### Figure 9: Anger Mediating the Effect of Tech Scandals on Regulatory Preferences, Issue Salience and Political Participation
#######################

Data$Treatment_Group_numeric <- ifelse(Data$Treatment_Group == "Control", 0, 1)

### Mediation and Sensitivity Analysis for Regulatory Preferences

model.m <- lm(Angry ~ Treatment_Group_numeric + age + gender + Income + educ_fourlevels + lr + Country, data = Data)
model.y <- lm(tech_reg_score_factor_WaveB_4item ~ Angry + Treatment_Group_numeric + age + gender + Income + educ_fourlevels + lr + Country, data = Data)

out.1 <- mediate(model.m, model.y, sims = 1000, boot = TRUE, treat = "Treatment_Group_numeric", mediator = "Angry")

summary(out.1)
summary(model.m)
summary(model.y)

### Sensitivity Analysis 

med.cont1 <- mediate(model.m, model.y, sims=100, treat = "Treatment_Group_numeric", mediator = "Angry")
sens.cont1 <- medsens(med.cont1, rho.by = 0.1)

summary(sens.cont1)



### Mediation and Sensitivity Analysis for Issue Salience

model.m2 <- lm(Angry ~ Treatment_Group_numeric + age + gender + Income + educ_fourlevels + lr + Country, data = Data)
model.y2 <- lm(salience_tech_WaveB ~ Angry + Treatment_Group_numeric + age + gender + Income + educ_fourlevels + lr + Country, data = Data)

out.2 <- mediate(model.m, model.y, sims = 1000, boot = TRUE, treat = "Treatment_Group_numeric", mediator = "Angry")

summary(out.2)
summary(model.m2)
summary(model.y2)

### Sensitivity Analysis 

med.cont2 <- mediate(model.m2, model.y2, sims=100, treat = "Treatment_Group_numeric", mediator = "Angry")
sens.cont2 <- medsens(med.cont2, rho.by = 0.1)

summary(sens.cont2)



### Mediation and Sensitivity Analysis for Political Participation

model.m3 <- lm(Angry ~ Treatment_Group_numeric + age + gender + Income + educ_fourlevels + lr + Country, data = subset(Data, part_tech_factor_WaveB > -100))
model.y3 <- lm(part_tech_factor_WaveB ~ Angry + Treatment_Group_numeric + age + gender + Income + educ_fourlevels + lr + Country, data = subset(Data, part_tech_factor_WaveB > -100))

out.3 <- mediate(model.m3, model.y3, sims = 1000, boot = TRUE, treat = "Treatment_Group_numeric", mediator = "Angry")

summary(out.3)
summary(model.m3)
summary(model.y3)

### Sensitivity Analysis 

med.cont3 <- mediate(model.m3, model.y3, sims=100, treat = "Treatment_Group_numeric", mediator = "Angry")
sens.cont3 <- medsens(med.cont3, rho.by = 0.1)

summary(sens.cont3)


### Combined Plot with Three Sets of Mediation and Sensitivity Analyses ###

par(mfrow = c(2,3),         
    mar = c(4,4,3,1),       
    oma = c(0,0,1,0))       
plot(out.1,main="Mediation Analysis: \nRegulatory Preferences")
plot(out.2,main="Mediation Analysis: \nIssue Salience")
plot(out.3,main="Mediation Analysis: \nPolitical Participation")
plot(sens.cont1,main="Sensitivity Analysis")
plot(sens.cont2,main="Sensitivity Analysis")
plot(sens.cont3,main="Sensitivity Analysis")
par(mfrow=c(1,1))




#######################
#### Figure 10: Scandal Treatment Effect on Regulatory Preferences Among People with Differing Levels of Pre-Treatment Anger at Big Technology Firms
#######################

# Mutate data to produce groups based on high and low levels of initial anger at tech companies
Combo_filtered <- Data %>%
  mutate(angry_group = ifelse(Angry_tech > 2, "Above 3", "3 or Below")) %>%
  filter(!is.na(angry_group))   

# Run separate regressions by initial anger group
model_results <- Combo_filtered %>%
  group_by(angry_group) %>%
  do(tidy(lm(tech_reg_score_factor_WaveB_4item ~ Treatment_Group, data = .),
          conf.int = TRUE, conf.level = 0.90))

# Keep only the Treatment_Group coefficient
plot_data <- model_results %>%
  filter(term == "Treatment_GroupTech - Scandal") %>%  
  select(angry_group, estimate, conf.low, conf.high)

#Relabel before plotting
plot_data <- plot_data %>%
  mutate(angry_group = recode(angry_group,
                              "Above 3" = "High Initial Anger at Tech Firms",
                              "3 or Below" = "Low Initial Anger at Tech Firms"))

# Create the plot
ggplot(plot_data, aes(x = angry_group, y = estimate)) +
  geom_point(size = 3, color = "black") +
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high),
                width = 0.15, color = "black") +
  geom_hline(yintercept = 0, linetype = "dashed", color = "gray50") +
  labs(
    title = "",
    x = "",
    y = "Treatment Effect"
  ) +
  theme_classic(base_size = 13) +
  scale_y_continuous(limits = c(-0.10, 0.50)) +   
  coord_flip()  




#######################
#### Online Appendix C: Balance Test for Survey Sample
#######################

# Preliminary Code to Run Balance Tests

get_mean_sd <- function(vector){
  mean <- mean(vector, na.rm = T)
  sd <- sd(vector, na.rm = T)
  sem <- sd/(sqrt(length(vector)))
  output <- paste(round(mean, 3), " (", round(sem, 3), ")", collapse = "", sep = "")
  return(output)
}

# Switching gender into a numeric variable

Data$Gender_Numeric <- ifelse(Data$gender == "Female", 1, 0)

# Run Balance Tests

balance_data <- group_by(Data, Treatment_Group) %>%
  drop_na(age, gender, lr, educ_fourlevels, Income) %>%
  summarize(Age = get_mean_sd(age),
            Gender = get_mean_sd(Gender_Numeric), 
            Political_Orientation = get_mean_sd(as.numeric(lr)),
            Education_Level = get_mean_sd(as.numeric(educ_fourlevels)),
            Income = get_mean_sd(as.numeric(Income)))

balance_data


#######################
#### Online Appendix D – Validating the Technology Regulation Scale
#######################

# Creating variable sets 
vars_4 <- c("Tech_Regulation_2_WaveB", "Tech_Regulation_4_WaveB", "Tech_Regulation_5_WaveB",
            "Tech_Regulation_6_WaveB")                                                           # Four Item Variable Set
vars_6 <- c("Tech_Regulation_1_WaveB", "Tech_Regulation_2_WaveB", "Tech_Regulation_3_WaveB",
            "Tech_Regulation_4_WaveB", "Tech_Regulation_5_WaveB", "Tech_Regulation_6_WaveB")     # Six Item Variable Set

# Running factor analyses 
fa_4  <- fa(Data[, vars_4], nfactors = 1, rotate = "Promax", cor = "poly")
fa_6  <- fa(Data[, vars_6], nfactors = 1, rotate = "Promax", cor = "poly")


# Extract the factor loadings and placing them in the correct points with empty vectors as needed
load_4  <- as.numeric(as.matrix(fa_4$loadings)[, 1])
load_6  <- as.numeric(as.matrix(fa_6$loadings)[, 1])

Four_vals  <- rep(NA_real_, 6)
Six_vals  <- rep(NA_real_, 6)

Four_vals[c(2,4,5,6)] <- load_4[c(1,2,3,4)]
Six_vals[1:6] <- load_6[c(1,2,3,4,5,6)]

# Calculating Cronbach's alpha for each dataset 
df_4 <- Data %>% drop_na(all_of(vars_4)) %>% select(all_of(vars_4))
df_6 <- Data %>% drop_na(all_of(vars_6)) %>% select(all_of(vars_6))

alpha_4  <- cronbach.alpha(df_4)$alpha
alpha_6  <- cronbach.alpha(df_6)$alpha

# Build final table 
item_labels <- c(
  "Item 1",
  "Item 2",
  "Item 3",
  "Item 4",
  "Item 5",
  "Item 6"
)

table_loadings <- data.frame(
  `Cryptocurrency Regulation Items` = item_labels,
  `Factor Loading (4-item scale)` = sprintf("%.2f", Four_vals),
  `Factor Loading (6-item scale)` = sprintf("%.2f", Six_vals),
  stringsAsFactors = FALSE,
  check.names = FALSE
)

# Append Cronbach's alpha row
alpha_row <- data.frame(
  `Cryptocurrency Regulation Items` = "Cronbach's alpha",
  `Factor Loading (4-item scale)` = sprintf("%.2f", alpha_4),
  `Factor Loading (6-item scale)` = sprintf("%.2f", alpha_6),
  stringsAsFactors = FALSE,
  check.names = FALSE
)

final_table <- bind_rows(table_loadings, alpha_row)
final_table[ final_table == "NA" | is.na(final_table) ] <- "---"

# Print and save
print(final_table)


data.frame.x <-
  Data %>% 
  filter(Country == "DE") %>%
  drop_na(Tech_Regulation_1_WaveB, Tech_Regulation_2_WaveB, Tech_Regulation_3_WaveB, Tech_Regulation_4_WaveB, Tech_Regulation_5_WaveB, Tech_Regulation_6_WaveB) %>% 
  select(Tech_Regulation_2_WaveB, Tech_Regulation_4_WaveB, Tech_Regulation_5_WaveB, Tech_Regulation_6_WaveB)
cronbach.alpha(data.frame.x)



#######################
#### Online Appendix E – Effect of Scandal on Support for Tech Regulation
#######################

# Ensure Treatment_Group factor ordering 
Data <- Data %>%
  mutate(Treatment_Group = factor(Treatment_Group, levels = c("Control", "Tech - Scandal")))

# helper to compute 90% CI
compute_summary <- function(df, conf_level = 0.90) {
  n <- nrow(df)
  mean_x <- mean(df$tech_reg_score_factor_WaveB_4item, na.rm = TRUE)
  sd_x <- sd(df$tech_reg_score_factor_WaveB_4item, na.rm = TRUE)
  se <- sd_x / sqrt(n)
  alpha <- 1 - conf_level
  tcrit <- qt(1 - alpha/2, df = n - 1) # two-sided
  lower <- mean_x - tcrit * se
  upper <- mean_x + tcrit * se
  tibble(count = n, mean = mean_x, sd = sd_x, lower = lower, upper = upper)
}

# Pooled Data
pooled_summary <- Data %>%
  group_by(Treatment_Group) %>%
  do(compute_summary(.)) %>%
  ungroup() %>%
  mutate(
    row_label = paste("Pooled Sample -", as.character(Treatment_Group))
  ) %>%
  select(row_label, Treatment_Group, count, mean, sd, lower, upper)

# Country Level Data
by_country_summary <- Data %>%
  group_by(Country, Treatment_Group) %>%
  do(compute_summary(.)) %>%
  ungroup() %>%
  mutate(
    row_label = case_when(
      Country %in% c("US", "UK", "FR", "DE") ~ paste(Country, "-", as.character(Treatment_Group)),
      TRUE ~ paste(Country, "-", as.character(Treatment_Group))
    )
  ) %>%
  mutate(Country = factor(Country, levels = c("US", "UK", "FR", "DE"))) %>%
  arrange(Country, Treatment_Group) %>%
  select(row_label, Country, Treatment_Group, count, mean, sd, lower, upper)

# Combine rows 
pooled_ordered <- pooled_summary %>% arrange(Treatment_Group) # Control then Treatment
country_ordered <- by_country_summary %>% arrange(Country, Treatment_Group)

combined <- bind_rows(
  pooled_ordered %>% select(row_label, Treatment_Group, mean, sd, lower, upper),
  country_ordered %>% select(row_label, Treatment_Group, mean, sd, lower, upper)
) %>%
  mutate(
    mean = round(mean, 2),
    sd = round(sd, 2),
    lower = round(lower, 2),
    upper = round(upper, 2)
  )

# Run the regressions and extract p-values for final column
extract_treatment_p <- function(fit) {
  td <- tidy(fit)
  trm <- td %>% filter(str_detect(term, "^Treatment_Group"))
  if (nrow(trm) == 0) return(NA_real_)
  return(trm$p.value[1])
}

# pooled regression
fit_pooled <- lm(tech_reg_score_factor_WaveB_4item ~ Treatment_Group, data = Data)
p_pooled <- extract_treatment_p(fit_pooled)

# country-specific regressions
get_country_p <- function(country_code) {
  df_sub <- subset(Data, Country == country_code)
  if (nrow(df_sub) < 4 || length(unique(df_sub$Treatment_Group)) < 2) return(NA_real_)
  fit <- lm(tech_reg_score_factor_WaveB_4item ~ Treatment_Group, data = df_sub)
  extract_treatment_p(fit)
}

p_US <- get_country_p("US")
p_UK <- get_country_p("UK")
p_FR <- get_country_p("FR")
p_DE <- get_country_p("DE")

# format p-values
format_p <- function(p) {
  if (is.na(p)) return(NA_character_)
  if (p < 0.001) return("p = 0.000")
  return(paste0("p = ", formatC(p, format = "f", digits = 3)))
}

p_pooled_f <- format_p(p_pooled)
p_US_f <- format_p(p_US)
p_UK_f <- format_p(p_UK)
p_FR_f <- format_p(p_FR)
p_DE_f <- format_p(p_DE)

# Place p-values on the Treatment rows only 
combined <- combined %>% mutate(p_value = NA_character_)

# pooled treatment row
combined$p_value[ str_detect(combined$row_label, "^Pooled Sample -") & combined$Treatment_Group == "Tech - Scandal" ] <- p_pooled_f

# country treatment rows: detect Treatment group label "Tech - Scandal"
combined$p_value[ str_detect(combined$row_label, "^US -") & combined$Treatment_Group == "Tech - Scandal" ] <- p_US_f
combined$p_value[ str_detect(combined$row_label, "^UK -") & combined$Treatment_Group == "Tech - Scandal" ] <- p_UK_f
combined$p_value[ (str_detect(combined$row_label, "^FR -") | str_detect(combined$row_label, "^France -")) & combined$Treatment_Group == "Tech - Scandal" ] <- p_FR_f
combined$p_value[ (str_detect(combined$row_label, "^DE -") | str_detect(combined$row_label, "^Germany -")) & combined$Treatment_Group == "Tech - Scandal" ] <- p_DE_f

# Final formatting
Table_E1 <- combined %>%
  transmute(
    Row = row_label,
    `Mean Score` = mean,
    SD = sd,
    `Lower CI` = lower,
    `Upper CI` = upper,
    `Statistical Difference Between Control & Treatment` = p_value
  )

Table_E1 <- Table_E1 %>%
  mutate(`Statistical Difference Between Control & Treatment` =
           ifelse(is.na(`Statistical Difference Between Control & Treatment`),
                  "",
                  `Statistical Difference Between Control & Treatment`))

# Print and save
print(Table_E1)



#######################
#### Online Appendix F – Effect of Scandal on Anger
#######################

# helper to compute 90% CI 

compute_summary2 <- function(df, conf_level = 0.90) {
  n <- nrow(df)
  mean_x <- mean(df$Angry, na.rm = TRUE)
  sd_x <- sd(df$Angry, na.rm = TRUE)
  se <- sd_x / sqrt(n)
  alpha <- 1 - conf_level
  tcrit <- qt(1 - alpha/2, df = n - 1) # two-sided
  lower <- mean_x - tcrit * se
  upper <- mean_x + tcrit * se
  tibble(count = n, mean = mean_x, sd = sd_x, lower = lower, upper = upper)
}

# Pooled Data 
pooled_summary2 <- Data %>%
  group_by(Treatment_Group) %>%
  do(compute_summary2(.)) %>%
  ungroup() %>%
  mutate(
    row_label = paste("Pooled Sample -", as.character(Treatment_Group))
  ) %>%
  select(row_label, Treatment_Group, count, mean, sd, lower, upper)

# Country Level Data 
by_country_summary2 <- Data %>%
  group_by(Country, Treatment_Group) %>%
  do(compute_summary2(.)) %>%
  ungroup() %>%
  mutate(
    row_label = case_when(
      Country %in% c("US", "UK", "FR", "DE") ~ paste(Country, "-", as.character(Treatment_Group)),
      TRUE ~ paste(Country, "-", as.character(Treatment_Group))
    )
  ) %>%
  mutate(Country = factor(Country, levels = c("US", "UK", "FR", "DE"))) %>%
  arrange(Country, Treatment_Group) %>%
  select(row_label, Country, Treatment_Group, count, mean, sd, lower, upper)

# Combine rows
pooled_ordered2 <- pooled_summary2 %>% arrange(Treatment_Group) # Control then Treatment
country_ordered2 <- by_country_summary2 %>% arrange(Country, Treatment_Group)

combined2 <- bind_rows(
  pooled_ordered2 %>% select(row_label, Treatment_Group, mean, sd, lower, upper),
  country_ordered2 %>% select(row_label, Treatment_Group, mean, sd, lower, upper)
) %>%
  mutate(
    mean = round(mean, 2),
    sd = round(sd, 2),
    lower = round(lower, 2),
    upper = round(upper, 2)
  )

# Run the regressions and extract p-values for final column
extract_treatment_p2 <- function(fit) {
  td <- tidy(fit)
  trm <- td %>% filter(str_detect(term, "^Treatment_Group"))
  if (nrow(trm) == 0) return(NA_real_)
  return(trm$p.value[1])
}

# pooled regression 
fit_pooled2 <- lm(Angry ~ Treatment_Group, data = Data)
p_pooled2 <- extract_treatment_p2(fit_pooled2)

# country-specific regressions
get_country_p2 <- function(country_code) {
  df_sub <- subset(Data, Country == country_code)
  if (nrow(df_sub) < 4 || length(unique(df_sub$Treatment_Group)) < 2) return(NA_real_)
  fit <- lm(Angry ~ Treatment_Group, data = df_sub)
  extract_treatment_p2(fit)
}

p_US2 <- get_country_p2("US")
p_UK2 <- get_country_p2("UK")
p_FR2 <- get_country_p2("FR")
p_DE2 <- get_country_p2("DE")

# format p-values (renamed)
format_p2 <- function(p) {
  if (is.na(p)) return(NA_character_)
  if (p < 0.001) return("p = 0.000")
  return(paste0("p = ", formatC(p, format = "f", digits = 3)))
}

p_pooled2_f <- format_p2(p_pooled2)
p_US2_f <- format_p2(p_US2)
p_UK2_f <- format_p2(p_UK2)
p_FR2_f <- format_p2(p_FR2)
p_DE2_f <- format_p2(p_DE2)

# Place p-values on the Treatment rows only
combined2 <- combined2 %>% mutate(p_value = NA_character_)

# pooled treatment row
combined2$p_value[ str_detect(combined2$row_label, "^Pooled Sample -") & combined2$Treatment_Group == "Tech - Scandal" ] <- p_pooled2_f

# country treatment rows: detect Treatment group label "Tech - Scandal"
combined2$p_value[ str_detect(combined2$row_label, "^US -") & combined2$Treatment_Group == "Tech - Scandal" ] <- p_US2_f
combined2$p_value[ str_detect(combined2$row_label, "^UK -") & combined2$Treatment_Group == "Tech - Scandal" ] <- p_UK2_f
combined2$p_value[ (str_detect(combined2$row_label, "^FR -") | str_detect(combined2$row_label, "^France -")) & combined2$Treatment_Group == "Tech - Scandal" ] <- p_FR2_f
combined2$p_value[ (str_detect(combined2$row_label, "^DE -") | str_detect(combined2$row_label, "^Germany -")) & combined2$Treatment_Group == "Tech - Scandal" ] <- p_DE2_f

# Final formatting 
Table_F1 <- combined2 %>%
  transmute(
    Row = row_label,
    `Mean Score` = mean,
    SD = sd,
    `Lower CI` = lower,
    `Upper CI` = upper,
    `Statistical Difference Between Control & Treatment` = p_value
  )

Table_F1 <- Table_F1 %>%
  mutate(`Statistical Difference Between Control & Treatment` =
           ifelse(is.na(`Statistical Difference Between Control & Treatment`),
                  "",
                  `Statistical Difference Between Control & Treatment`))

# Print and save 
print(Table_F1)




#######################
#### Online Appendix G – Mediation Analysis Results
#######################

# Model A – Anger Mediating Support for Tech Regulation

summary(model.m) # DV = Anger
summary(model.y) # DV = Tech Regulation
summary(out.1)   # Full Mediation Results and ACME Figure

# Model B – Anger Mediating Issue Salience

summary(model.m2) # DV = Anger
summary(model.y2) # DV = Issue Salience
summary(out.2)   # Full Mediation Results and ACME Figure

# Model C – Anger Mediating Political Participation

summary(model.m3) # DV = Anger
summary(model.y3) # DV = Political Participation
summary(out.3)   # Full Mediation Results and ACME Figure


### The code below puts the above models in the format shown in Table G1 of Appendix G

# This function reads capture.output(summary(med_obj)) and returns formatted strings.
parse_mediation_for_stargazer <- function(med_obj, digits = 3) {
  if (is.null(med_obj)) return(c(ACME = "", Direct = "", Total = "", Prop = ""))
  txt <- capture.output(summary(med_obj))
  if (length(txt) == 0) return(c(ACME = "", Direct = "", Total = "", Prop = ""))
  
  header_idx <- which(sapply(txt, function(line) {
    ll <- tolower(line)
    (str_detect(ll, "estimate") && (str_detect(ll, "95% ci") || str_detect(ll, "95% ci lower") || str_detect(ll, "95% ci upper")))
  }))
  if (length(header_idx) == 0) {
    header_idx <- which(sapply(txt, function(line) str_detect(tolower(line), "estimate")))
  }
  header_idx <- if (length(header_idx) > 0) header_idx[1] else NA_integer_
  
  if (is.na(header_idx)) {
    candidate_idx <- which(sapply(txt, function(line) str_detect(tolower(line), "acme|average causal mediation effect")))
    header_idx <- if (length(candidate_idx) > 0) candidate_idx[1] - 1 else NA_integer_
  }
  
  start <- if (!is.na(header_idx)) header_idx + 1 else 1
  end <- min(length(txt), start + 10)  
  block <- txt[start:end]
  
  extract_nums <- function(line) {
    nums <- str_extract_all(line, "[-+]?[0-9]*\\.?[0-9]+(?:[eE][-+]?[0-9]+)?")[[1]]
    as.numeric(nums)
  }
  
  find_line_by_key <- function(keys) {
    idx <- which(sapply(block, function(l) any(sapply(keys, function(k) str_detect(tolower(l), paste0("^\\s*", tolower(k)))))))
    if (length(idx) == 0) {
      idx <- which(sapply(block, function(l) any(sapply(keys, function(k) str_detect(tolower(l), tolower(k))))))
    }
    if (length(idx) == 0) return(NA_integer_) else return(idx[1])
  }
  
  acme_i  <- find_line_by_key(c("ACME", "average causal mediation effect"))
  ade_i   <- find_line_by_key(c("ADE", "average direct effect", "direct effect"))
  total_i <- find_line_by_key(c("total effect"))
  prop_i  <- find_line_by_key(c("prop.", "proportion mediated", "prop mediated"))
  
  parse_row <- function(i) {
    if (is.na(i)) return(list(est = NA_real_, low = NA_real_, high = NA_real_))
    nums <- extract_nums(block[i])
    est <- if (length(nums) >= 1) nums[1] else NA_real_
    low <- if (length(nums) >= 2) nums[2] else NA_real_
    high <- if (length(nums) >= 3) nums[3] else NA_real_
    list(est = est, low = low, high = high)
  }
  
  a <- parse_row(acme_i)
  d <- parse_row(ade_i)
  t <- parse_row(total_i)
  
  prop_val <- NA_real_
  if (!is.na(prop_i)) {
    nums_prop <- extract_nums(block[prop_i])
    if (length(nums_prop) >= 1) prop_val <- nums_prop[1]
  }
  
  fmt_ci <- function(x) {
    if (is.na(x$est)) return("")
    low_s <- ifelse(is.na(x$low), "NA", formatC(x$low, format = "f", digits = digits))
    high_s <- ifelse(is.na(x$high), "NA", formatC(x$high, format = "f", digits = digits))
    sprintf("%s [%s, %s]", formatC(x$est, format = "f", digits = digits), low_s, high_s)
  }
  
  c(
    ACME   = fmt_ci(a),
    Direct = fmt_ci(d),
    Total  = fmt_ci(t),
    Prop   = ifelse(is.na(prop_val), "", formatC(prop_val, format = "f", digits = digits))
  )
}

# sample sizes helper 
get_n <- function(mod) {
  tryCatch({
    nrow(model.frame(mod))
  }, error = function(e) NA_integer_)
}

# extract mediation summaries for models A, B, C

medA <- parse_mediation_for_stargazer(out.1, digits = 3)
medB <- parse_mediation_for_stargazer(out.2, digits = 3)
medC <- parse_mediation_for_stargazer(out.3, digits = 3)

# create add.lines entries (place mediation results under Yi columns 2,4,6)

add_lines_list <- list(
  c("ACME (95% CI)",
    "", medA["ACME"],
    "", medB["ACME"],
    "", medC["ACME"]
  ),
  c("Direct Effect (95% CI)",
    "", medA["Direct"],
    "", medB["Direct"],
    "", medC["Direct"]
  ),
  c("Total Effect (95% CI)",
    "", medA["Total"],
    "", medB["Total"],
    "", medC["Total"]
  ),
  c("Prop. Mediated",
    "", medA["Prop"],
    "", medB["Prop"],
    "", medC["Prop"]
  ),
  c("N (Mi)", as.character(get_n(model.m)), "", as.character(get_n(model.m2)), "", as.character(get_n(model.m3))),
  c("N (Yi)", "", as.character(get_n(model.y)), "", as.character(get_n(model.y2)), "", as.character(get_n(model.y3)))
)

# Edit add_lines_list to avoid NA issues in stargazer

n_models <- 6
sanitize_add_line <- function(line) {
  line <- as.character(line)
  line[is.na(line)] <- ""
  if (length(line) < (n_models + 1)) line <- c(line, rep("", (n_models + 1) - length(line)))
  if (length(line) > (n_models + 1)) line <- line[1:(n_models + 1)]
  return(line)
}
add_lines_list <- lapply(add_lines_list, sanitize_add_line)

# Final stargazer call to create table

stargazer(
  model.m, model.y, model.m2, model.y2, model.m3, model.y3,
  type = "text",
  #out = "Table_G1.txt",      # This line creates a .txt file with the full table in a clean output
  title = "Anger Mediation on Support for Technology Regulation, Issue Salience and Political Participation",
  column.labels = c(
    "Model A (DV=Anger)",
    "Model A (DV=Regulation)",
    "Model B (DV=Anger)",
    "Model B (DV=Salience)",
    "Model C (DV=Anger)",
    "Model C (DV=Participation)"
  ),
  dep.var.labels.include = FALSE,
  dep.var.caption = "",
  omit = c("Country"),
  omit.stat = c("rsq"),
  keep.stat = c("n"),
  star.cutoffs = c(0.05, 0.01, 0.001),
  add.lines = add_lines_list,
  no.space = TRUE,
  single.row = FALSE,
  covariate.labels=c("Anger","Exposure to Scandal Treatment", "Age", "Gender", 
                     "Income", "Education", "Political Orientation", "Constant"))





#######################
#### Online Appendix H – Effect of Scandal on Issue Salience
#######################

# helper to compute 90% CI 

compute_summary3 <- function(df, conf_level = 0.90) {
  n <- nrow(df)
  mean_x <- mean(df$salience_tech_WaveB, na.rm = TRUE)
  sd_x <- sd(df$salience_tech_WaveB, na.rm = TRUE)
  se <- sd_x / sqrt(n)
  alpha <- 1 - conf_level
  tcrit <- qt(1 - alpha/2, df = n - 1) # two-sided
  lower <- mean_x - tcrit * se
  upper <- mean_x + tcrit * se
  tibble(count = n, mean = mean_x, sd = sd_x, lower = lower, upper = upper)
}

# Pooled Data 
pooled_summary3 <- Data %>%
  group_by(Treatment_Group) %>%
  do(compute_summary3(.)) %>%
  ungroup() %>%
  mutate(
    row_label = paste("Pooled Sample -", as.character(Treatment_Group))
  ) %>%
  select(row_label, Treatment_Group, count, mean, sd, lower, upper)

# Country Level Data 
by_country_summary3 <- Data %>%
  group_by(Country, Treatment_Group) %>%
  do(compute_summary3(.)) %>%
  ungroup() %>%
  mutate(
    row_label = case_when(
      Country %in% c("US", "UK", "FR", "DE") ~ paste(Country, "-", as.character(Treatment_Group)),
      TRUE ~ paste(Country, "-", as.character(Treatment_Group))
    )
  ) %>%
  mutate(Country = factor(Country, levels = c("US", "UK", "FR", "DE"))) %>%
  arrange(Country, Treatment_Group) %>%
  select(row_label, Country, Treatment_Group, count, mean, sd, lower, upper)

# Combine rows
pooled_ordered3 <- pooled_summary3 %>% arrange(Treatment_Group) # Control then Treatment
country_ordered3 <- by_country_summary3 %>% arrange(Country, Treatment_Group)

combined3 <- bind_rows(
  pooled_ordered3 %>% select(row_label, Treatment_Group, mean, sd, lower, upper),
  country_ordered3 %>% select(row_label, Treatment_Group, mean, sd, lower, upper)
) %>%
  mutate(
    mean = round(mean, 2),
    sd = round(sd, 2),
    lower = round(lower, 2),
    upper = round(upper, 2)
  )

# Run the regressions and extract p-values for final column
extract_treatment_p3 <- function(fit) {
  td <- tidy(fit)
  trm <- td %>% filter(str_detect(term, "^Treatment_Group"))
  if (nrow(trm) == 0) return(NA_real_)
  return(trm$p.value[1])
}

# pooled regression 
fit_pooled3 <- lm(salience_tech_WaveB ~ Treatment_Group, data = Data)
p_pooled3 <- extract_treatment_p3(fit_pooled3)

# country-specific regressions
get_country_p3 <- function(country_code) {
  df_sub <- subset(Data, Country == country_code)
  if (nrow(df_sub) < 4 || length(unique(df_sub$Treatment_Group)) < 2) return(NA_real_)
  fit <- lm(salience_tech_WaveB ~ Treatment_Group, data = df_sub)
  extract_treatment_p3(fit)
}

p_US3 <- get_country_p3("US")
p_UK3 <- get_country_p3("UK")
p_FR3 <- get_country_p3("FR")
p_DE3 <- get_country_p3("DE")

# format p-values (renamed)
format_p3 <- function(p) {
  if (is.na(p)) return(NA_character_)
  if (p < 0.001) return("p = 0.000")
  return(paste0("p = ", formatC(p, format = "f", digits = 3)))
}

p_pooled3_f <- format_p3(p_pooled3)
p_US3_f <- format_p3(p_US3)
p_UK3_f <- format_p3(p_UK3)
p_FR3_f <- format_p3(p_FR3)
p_DE3_f <- format_p3(p_DE3)

# Place p-values on the Treatment rows only
combined3 <- combined3 %>% mutate(p_value = NA_character_)

# pooled treatment row
combined3$p_value[ str_detect(combined3$row_label, "^Pooled Sample -") & combined3$Treatment_Group == "Tech - Scandal" ] <- p_pooled3_f

# country treatment rows: detect Treatment group label "Tech - Scandal"
combined3$p_value[ str_detect(combined3$row_label, "^US -") & combined3$Treatment_Group == "Tech - Scandal" ] <- p_US3_f
combined3$p_value[ str_detect(combined3$row_label, "^UK -") & combined3$Treatment_Group == "Tech - Scandal" ] <- p_UK3_f
combined3$p_value[ (str_detect(combined3$row_label, "^FR -") | str_detect(combined3$row_label, "^France -")) & combined3$Treatment_Group == "Tech - Scandal" ] <- p_FR3_f
combined3$p_value[ (str_detect(combined3$row_label, "^DE -") | str_detect(combined3$row_label, "^Germany -")) & combined3$Treatment_Group == "Tech - Scandal" ] <- p_DE3_f

# Final formatting 
Table_H1 <- combined3 %>%
  transmute(
    Row = row_label,
    `Mean Score` = mean,
    SD = sd,
    `Lower CI` = lower,
    `Upper CI` = upper,
    `Statistical Difference Between Control & Treatment` = p_value
  )

Table_H1 <- Table_H1 %>%
  mutate(`Statistical Difference Between Control & Treatment` =
           ifelse(is.na(`Statistical Difference Between Control & Treatment`),
                  "",
                  `Statistical Difference Between Control & Treatment`))

# Print and save 
print(Table_H1)






#######################
#### Online Appendix I – Effect of Scandal on Political Participation
#######################

# helper to compute 90% CI 

compute_summary4 <- function(df, conf_level = 0.90) {
  n <- nrow(df)
  mean_x <- mean(df$part_tech_factor_WaveB, na.rm = TRUE)
  sd_x <- sd(df$part_tech_factor_WaveB, na.rm = TRUE)
  se <- sd_x / sqrt(n)
  alpha <- 1 - conf_level
  tcrit <- qt(1 - alpha/2, df = n - 1) # two-sided
  lower <- mean_x - tcrit * se
  upper <- mean_x + tcrit * se
  tibble(count = n, mean = mean_x, sd = sd_x, lower = lower, upper = upper)
}

# Pooled Data 
pooled_summary4 <- Data %>%
  group_by(Treatment_Group) %>%
  do(compute_summary4(.)) %>%
  ungroup() %>%
  mutate(
    row_label = paste("Pooled Sample -", as.character(Treatment_Group))
  ) %>%
  select(row_label, Treatment_Group, count, mean, sd, lower, upper)

# Country Level Data 
by_country_summary4 <- Data %>%
  group_by(Country, Treatment_Group) %>%
  do(compute_summary4(.)) %>%
  ungroup() %>%
  mutate(
    row_label = case_when(
      Country %in% c("US", "UK", "FR", "DE") ~ paste(Country, "-", as.character(Treatment_Group)),
      TRUE ~ paste(Country, "-", as.character(Treatment_Group))
    )
  ) %>%
  mutate(Country = factor(Country, levels = c("US", "UK", "FR", "DE"))) %>%
  arrange(Country, Treatment_Group) %>%
  select(row_label, Country, Treatment_Group, count, mean, sd, lower, upper)

# Combine rows
pooled_ordered4 <- pooled_summary4 %>% arrange(Treatment_Group) # Control then Treatment
country_ordered4 <- by_country_summary4 %>% arrange(Country, Treatment_Group)

combined4 <- bind_rows(
  pooled_ordered4 %>% select(row_label, Treatment_Group, mean, sd, lower, upper),
  country_ordered4 %>% select(row_label, Treatment_Group, mean, sd, lower, upper)
) %>%
  mutate(
    mean = round(mean, 2),
    sd = round(sd, 2),
    lower = round(lower, 2),
    upper = round(upper, 2)
  )

# Run the regressions and extract p-values for final column
extract_treatment_p4 <- function(fit) {
  td <- tidy(fit)
  trm <- td %>% filter(str_detect(term, "^Treatment_Group"))
  if (nrow(trm) == 0) return(NA_real_)
  return(trm$p.value[1])
}

# pooled regression 
fit_pooled4 <- lm(part_tech_factor_WaveB ~ Treatment_Group, data = Data)
p_pooled4 <- extract_treatment_p4(fit_pooled4)

# country-specific regressions
get_country_p4 <- function(country_code) {
  df_sub <- subset(Data, Country == country_code)
  if (nrow(df_sub) < 4 || length(unique(df_sub$Treatment_Group)) < 2) return(NA_real_)
  fit <- lm(part_tech_factor_WaveB ~ Treatment_Group, data = df_sub)
  extract_treatment_p4(fit)
}

p_US4 <- get_country_p4("US")
p_UK4 <- get_country_p4("UK")
p_FR4 <- get_country_p4("FR")
p_DE4 <- get_country_p4("DE")

# format p-values (renamed)
format_p4 <- function(p) {
  if (is.na(p)) return(NA_character_)
  if (p < 0.001) return("p = 0.000")
  return(paste0("p = ", formatC(p, format = "f", digits = 3)))
}

p_pooled4_f <- format_p4(p_pooled4)
p_US4_f <- format_p4(p_US4)
p_UK4_f <- format_p4(p_UK4)
p_FR4_f <- format_p4(p_FR4)
p_DE4_f <- format_p4(p_DE4)

# Place p-values on the Treatment rows only
combined4 <- combined4 %>% mutate(p_value = NA_character_)

# pooled treatment row
combined4$p_value[ str_detect(combined4$row_label, "^Pooled Sample -") & combined4$Treatment_Group == "Tech - Scandal" ] <- p_pooled4_f

# country treatment rows: detect Treatment group label "Tech - Scandal"
combined4$p_value[ str_detect(combined4$row_label, "^US -") & combined4$Treatment_Group == "Tech - Scandal" ] <- p_US4_f
combined4$p_value[ str_detect(combined4$row_label, "^UK -") & combined4$Treatment_Group == "Tech - Scandal" ] <- p_UK4_f
combined4$p_value[ (str_detect(combined4$row_label, "^FR -") | str_detect(combined4$row_label, "^France -")) & combined4$Treatment_Group == "Tech - Scandal" ] <- p_FR4_f
combined4$p_value[ (str_detect(combined4$row_label, "^DE -") | str_detect(combined4$row_label, "^Germany -")) & combined4$Treatment_Group == "Tech - Scandal" ] <- p_DE4_f

# Final formatting 
Table_I1 <- combined4 %>%
  transmute(
    Row = row_label,
    `Mean Score` = mean,
    SD = sd,
    `Lower CI` = lower,
    `Upper CI` = upper,
    `Statistical Difference Between Control & Treatment` = p_value
  )

Table_I1 <- Table_I1 %>%
  mutate(`Statistical Difference Between Control & Treatment` =
           ifelse(is.na(`Statistical Difference Between Control & Treatment`),
                  "",
                  `Statistical Difference Between Control & Treatment`))

# Print and save 
print(Table_I1)






#######################
#### Online Appendix J – Effect of Scandal on Regulatory Preferences by Persuasion Pathways and Country
#######################

# Assigning respondents to persuasion pathway groups

Data$Quadrants99 <- 
  ifelse(Data$Pre_Treatment_Aware_Tech == "Unaware" & (Data$Interest_Alignment_Country2 == "High Alignment" & Data$Trust_Tech_WaveA_HL_Country_v2 == "High Trust"), "Learner",
         ifelse(Data$Pre_Treatment_Aware_Tech == "Aware" & (Data$Interest_Alignment_Country2 == "Low Alignment" | Data$Trust_Tech_WaveA_HL_Country_v2 == "Low Trust"), "Primer",
                ifelse(Data$Pre_Treatment_Aware_Tech == "Unaware" & (Data$Interest_Alignment_Country2 == "Low Alignment" | Data$Trust_Tech_WaveA_HL_Country_v2 == "Low Trust"), "Primer_and_Learner", 
                       "Non_Learner_Non_Primer")))

#### Figure J1 - Pooled Sample - Comparing Treatment Effects in All Quadrants

combo_tech_scandal1 <- -wtd.t.test(subset(Data,Quadrants99 == "Learner" &  Treatment_Group == "Control" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item, subset(Data,Quadrants99 == "Learner" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item,
                                   weight=subset(Data,Quadrants99 == "Learner" &  Treatment_Group == "Control" & Sector == "Technology Sector")$cross_weight,weighty=subset(Data,Quadrants99 == "Learner" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$cross_weight,samedata=F)$additional[1]
combo_tech_scandal_se1 <- wtd.t.test(subset(Data,Quadrants99 == "Learner" &  Treatment_Group == "Control" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item, subset(Data,Quadrants99 == "Learner" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item,
                                     weight=subset(Data,Quadrants99 == "Learner" &  Treatment_Group == "Control" & Sector == "Technology Sector")$cross_weight,weighty=subset(Data,Quadrants99 == "Learner" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$cross_weight,samedata=F)$additional[4]

combo_tech_scandal2 <- -wtd.t.test(subset(Data,Quadrants99 == "Primer" &  Treatment_Group == "Control" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item, subset(Data,Quadrants99 == "Primer" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item,
                                   weight=subset(Data,Quadrants99 == "Primer" &  Treatment_Group == "Control" & Sector == "Technology Sector")$cross_weight,weighty=subset(Data,Quadrants99 == "Primer" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$cross_weight,samedata=F)$additional[1]
combo_tech_scandal_se2 <- wtd.t.test(subset(Data,Quadrants99 == "Primer" &  Treatment_Group == "Control" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item, subset(Data,Quadrants99 == "Primer" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item,
                                     weight=subset(Data,Quadrants99 == "Primer" &  Treatment_Group == "Control" & Sector == "Technology Sector")$cross_weight,weighty=subset(Data,Quadrants99 == "Primer" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$cross_weight,samedata=F)$additional[4]

combo_tech_scandal3 <- -wtd.t.test(subset(Data,Quadrants99 == "Primer_and_Learner" &  Treatment_Group == "Control" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item, subset(Data,Quadrants99 == "Primer_and_Learner" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item,
                                   weight=subset(Data,Quadrants99 == "Primer_and_Learner" &  Treatment_Group == "Control" & Sector == "Technology Sector")$cross_weight,weighty=subset(Data,Quadrants99 == "Primer_and_Learner" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$cross_weight,samedata=F)$additional[1]
combo_tech_scandal_se3 <- wtd.t.test(subset(Data,Quadrants99 == "Primer_and_Learner" &  Treatment_Group == "Control" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item, subset(Data,Quadrants99 == "Primer_and_Learner" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item,
                                     weight=subset(Data,Quadrants99 == "Primer_and_Learner" &  Treatment_Group == "Control" & Sector == "Technology Sector")$cross_weight,weighty=subset(Data,Quadrants99 == "Primer_and_Learner" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$cross_weight,samedata=F)$additional[4]

combo_tech_scandal4 <- -wtd.t.test(subset(Data,Quadrants99 == "Non_Learner_Non_Primer" &  Treatment_Group == "Control" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item, subset(Data,Quadrants99 == "Non_Learner_Non_Primer" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item,
                                   weight=subset(Data,Quadrants99 == "Non_Learner_Non_Primer" &  Treatment_Group == "Control" & Sector == "Technology Sector")$cross_weight,weighty=subset(Data,Quadrants99 == "Non_Learner_Non_Primer" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$cross_weight,samedata=F)$additional[1]
combo_tech_scandal_se4 <- wtd.t.test(subset(Data,Quadrants99 == "Non_Learner_Non_Primer" &  Treatment_Group == "Control" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item, subset(Data,Quadrants99 == "Non_Learner_Non_Primer" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item,
                                     weight=subset(Data,Quadrants99 == "Non_Learner_Non_Primer" &  Treatment_Group == "Control" & Sector == "Technology Sector")$cross_weight,weighty=subset(Data,Quadrants99 == "Non_Learner_Non_Primer" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$cross_weight,samedata=F)$additional[4]

par(mar=c(3.1,6.1,3.5,2.1))
plot(x=c(),y=c(),ylim=c(-0.2,0.7),xlim=c(0.42,0.52), ylab="Treatment Effect", main="", xaxt="n", xlab="",cex.lab=1.2)

points(0.44,combo_tech_scandal1,pch=16, col = "black")
lines(x=c(0.44,0.44),y=c(combo_tech_scandal1-1.68*combo_tech_scandal_se1,combo_tech_scandal1+1.68*combo_tech_scandal_se1),lwd=2, col = "black")
points(0.46,combo_tech_scandal2,pch=16, col = "black")
lines(x=c(0.46,0.46),y=c(combo_tech_scandal2-1.68*combo_tech_scandal_se2,combo_tech_scandal2+1.68*combo_tech_scandal_se2),lwd=2, col = "black")
points(0.48,combo_tech_scandal3,pch=16, col = "black")
lines(x=c(0.48,0.48),y=c(combo_tech_scandal3-1.68*combo_tech_scandal_se3,combo_tech_scandal3+1.68*combo_tech_scandal_se3),lwd=2, col = "black")
points(0.50,combo_tech_scandal4,pch=16, col = "black")
lines(x=c(0.50,0.50),y=c(combo_tech_scandal4-1.68*combo_tech_scandal_se4,combo_tech_scandal4+1.68*combo_tech_scandal_se4),lwd=2, col = "black")

abline(h=0,lty="dashed")
axis(1, at=seq(0.44,0.50,by=0.02), labels = FALSE)
text(seq(0.44,0.50,by=0.02), par("usr")[3] - 0.03, labels = c("Uninformed", "Low Trust", "Low Trust & \nUninformed", "High Trust & \nInformed"), srt = 0, pos = 1, xpd = TRUE,cex=0.8)




#### Figure J2 - Pooled Sample - Comparing Treatment Effects in All Quadrants

# Country level results for respondents designated as uninformed

us_tech_scandal1 <- -wtd.t.test(subset(Data, Country == "US" & Quadrants99 == "Learner" &  Treatment_Group == "Control" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item, subset(Data, Country == "US" & Quadrants99 == "Learner" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item,
                                weight=subset(Data, Country == "US" & Quadrants99 == "Learner" &  Treatment_Group == "Control" & Sector == "Technology Sector")$cross_weight,weighty=subset(Data, Country == "US" & Quadrants99 == "Learner" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$cross_weight,samedata=F)$additional[1]
us_tech_scandal_se1 <- wtd.t.test(subset(Data, Country == "US" & Quadrants99 == "Learner" &  Treatment_Group == "Control" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item, subset(Data, Country == "US" & Quadrants99 == "Learner" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item,
                                  weight=subset(Data, Country == "US" & Quadrants99 == "Learner" &  Treatment_Group == "Control" & Sector == "Technology Sector")$cross_weight,weighty=subset(Data, Country == "US" & Quadrants99 == "Learner" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$cross_weight,samedata=F)$additional[4]

uk_tech_scandal1 <- -wtd.t.test(subset(Data, Country == "UK" & Quadrants99 == "Learner" &  Treatment_Group == "Control" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item, subset(Data, Country == "UK" & Quadrants99 == "Learner" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item,
                                weight=subset(Data, Country == "UK" & Quadrants99 == "Learner" &  Treatment_Group == "Control" & Sector == "Technology Sector")$cross_weight,weighty=subset(Data, Country == "UK" & Quadrants99 == "Learner" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$cross_weight,samedata=F)$additional[1]
uk_tech_scandal_se1 <- wtd.t.test(subset(Data, Country == "UK" & Quadrants99 == "Learner" &  Treatment_Group == "Control" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item, subset(Data, Country == "UK" & Quadrants99 == "Learner" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item,
                                  weight=subset(Data, Country == "UK" & Quadrants99 == "Learner" &  Treatment_Group == "Control" & Sector == "Technology Sector")$cross_weight,weighty=subset(Data, Country == "UK" & Quadrants99 == "Learner" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$cross_weight,samedata=F)$additional[4]

fr_tech_scandal1 <- -wtd.t.test(subset(Data, Country == "FR" & Quadrants99 == "Learner" &  Treatment_Group == "Control" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item, subset(Data, Country == "FR" & Quadrants99 == "Learner" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item,
                                weight=subset(Data, Country == "FR" & Quadrants99 == "Learner" &  Treatment_Group == "Control" & Sector == "Technology Sector")$cross_weight,weighty=subset(Data, Country == "FR" & Quadrants99 == "Learner" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$cross_weight,samedata=F)$additional[1]
fr_tech_scandal_se1 <- wtd.t.test(subset(Data, Country == "FR" & Quadrants99 == "Learner" &  Treatment_Group == "Control" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item, subset(Data, Country == "FR" & Quadrants99 == "Learner" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item,
                                  weight=subset(Data, Country == "FR" & Quadrants99 == "Learner" &  Treatment_Group == "Control" & Sector == "Technology Sector")$cross_weight,weighty=subset(Data, Country == "FR" & Quadrants99 == "Learner" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$cross_weight,samedata=F)$additional[4]

de_tech_scandal1 <- -wtd.t.test(subset(Data, Country == "DE" & Quadrants99 == "Learner" &  Treatment_Group == "Control" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item, subset(Data, Country == "DE" & Quadrants99 == "Learner" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item,
                                weight=subset(Data, Country == "DE" & Quadrants99 == "Learner" &  Treatment_Group == "Control" & Sector == "Technology Sector")$cross_weight,weighty=subset(Data, Country == "DE" & Quadrants99 == "Learner" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$cross_weight,samedata=F)$additional[1]
de_tech_scandal_se1 <- wtd.t.test(subset(Data, Country == "DE" & Quadrants99 == "Learner" &  Treatment_Group == "Control" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item, subset(Data, Country == "DE" & Quadrants99 == "Learner" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item,
                                  weight=subset(Data, Country == "DE" & Quadrants99 == "Learner" &  Treatment_Group == "Control" & Sector == "Technology Sector")$cross_weight,weighty=subset(Data, Country == "DE" & Quadrants99 == "Learner" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$cross_weight,samedata=F)$additional[4]

# Country level results for respondents designated as Low Trust

us_tech_scandal2 <- -wtd.t.test(subset(Data, Country == "US" & Quadrants99 == "Primer" &  Treatment_Group == "Control" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item, subset(Data, Country == "US" & Quadrants99 == "Primer" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item,
                                weight=subset(Data, Country == "US" & Quadrants99 == "Primer" &  Treatment_Group == "Control" & Sector == "Technology Sector")$cross_weight,weighty=subset(Data, Country == "US" & Quadrants99 == "Primer" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$cross_weight,samedata=F)$additional[1]
us_tech_scandal_se2 <- wtd.t.test(subset(Data, Country == "US" & Quadrants99 == "Primer" &  Treatment_Group == "Control" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item, subset(Data, Country == "US" & Quadrants99 == "Primer" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item,
                                  weight=subset(Data, Country == "US" & Quadrants99 == "Primer" &  Treatment_Group == "Control" & Sector == "Technology Sector")$cross_weight,weighty=subset(Data, Country == "US" & Quadrants99 == "Primer" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$cross_weight,samedata=F)$additional[4]

uk_tech_scandal2 <- -wtd.t.test(subset(Data, Country == "UK" & Quadrants99 == "Primer" &  Treatment_Group == "Control" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item, subset(Data, Country == "UK" & Quadrants99 == "Primer" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item,
                                weight=subset(Data, Country == "UK" & Quadrants99 == "Primer" &  Treatment_Group == "Control" & Sector == "Technology Sector")$cross_weight,weighty=subset(Data, Country == "UK" & Quadrants99 == "Primer" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$cross_weight,samedata=F)$additional[1]
uk_tech_scandal_se2 <- wtd.t.test(subset(Data, Country == "UK" & Quadrants99 == "Primer" &  Treatment_Group == "Control" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item, subset(Data, Country == "UK" & Quadrants99 == "Primer" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item,
                                  weight=subset(Data, Country == "UK" & Quadrants99 == "Primer" &  Treatment_Group == "Control" & Sector == "Technology Sector")$cross_weight,weighty=subset(Data, Country == "UK" & Quadrants99 == "Primer" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$cross_weight,samedata=F)$additional[4]

fr_tech_scandal2 <- -wtd.t.test(subset(Data, Country == "FR" & Quadrants99 == "Primer" &  Treatment_Group == "Control" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item, subset(Data, Country == "FR" & Quadrants99 == "Primer" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item,
                                weight=subset(Data, Country == "FR" & Quadrants99 == "Primer" &  Treatment_Group == "Control" & Sector == "Technology Sector")$cross_weight,weighty=subset(Data, Country == "FR" & Quadrants99 == "Primer" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$cross_weight,samedata=F)$additional[1]
fr_tech_scandal_se2 <- wtd.t.test(subset(Data, Country == "FR" & Quadrants99 == "Primer" &  Treatment_Group == "Control" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item, subset(Data, Country == "FR" & Quadrants99 == "Primer" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item,
                                  weight=subset(Data, Country == "FR" & Quadrants99 == "Primer" &  Treatment_Group == "Control" & Sector == "Technology Sector")$cross_weight,weighty=subset(Data, Country == "FR" & Quadrants99 == "Primer" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$cross_weight,samedata=F)$additional[4]

de_tech_scandal2 <- -wtd.t.test(subset(Data, Country == "DE" & Quadrants99 == "Primer" &  Treatment_Group == "Control" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item, subset(Data, Country == "DE" & Quadrants99 == "Primer" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item,
                                weight=subset(Data, Country == "DE" & Quadrants99 == "Primer" &  Treatment_Group == "Control" & Sector == "Technology Sector")$cross_weight,weighty=subset(Data, Country == "DE" & Quadrants99 == "Primer" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$cross_weight,samedata=F)$additional[1]
de_tech_scandal_se2 <- wtd.t.test(subset(Data, Country == "DE" & Quadrants99 == "Primer" &  Treatment_Group == "Control" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item, subset(Data, Country == "DE" & Quadrants99 == "Primer" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item,
                                  weight=subset(Data, Country == "DE" & Quadrants99 == "Primer" &  Treatment_Group == "Control" & Sector == "Technology Sector")$cross_weight,weighty=subset(Data, Country == "DE" & Quadrants99 == "Primer" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$cross_weight,samedata=F)$additional[4]

# Country level results for respondents designated as Low Trust and Uninformed

us_tech_scandal3 <- -wtd.t.test(subset(Data, Country == "US" & Quadrants99 == "Primer_and_Learner" &  Treatment_Group == "Control" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item, subset(Data, Country == "US" & Quadrants99 == "Primer_and_Learner" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item,
                                weight=subset(Data, Country == "US" & Quadrants99 == "Primer_and_Learner" &  Treatment_Group == "Control" & Sector == "Technology Sector")$cross_weight,weighty=subset(Data, Country == "US" & Quadrants99 == "Primer_and_Learner" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$cross_weight,samedata=F)$additional[1]
us_tech_scandal_se3 <- wtd.t.test(subset(Data, Country == "US" & Quadrants99 == "Primer_and_Learner" &  Treatment_Group == "Control" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item, subset(Data, Country == "US" & Quadrants99 == "Primer_and_Learner" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item,
                                  weight=subset(Data, Country == "US" & Quadrants99 == "Primer_and_Learner" &  Treatment_Group == "Control" & Sector == "Technology Sector")$cross_weight,weighty=subset(Data, Country == "US" & Quadrants99 == "Primer_and_Learner" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$cross_weight,samedata=F)$additional[4]

uk_tech_scandal3 <- -wtd.t.test(subset(Data, Country == "UK" & Quadrants99 == "Primer_and_Learner" &  Treatment_Group == "Control" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item, subset(Data, Country == "UK" & Quadrants99 == "Primer_and_Learner" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item,
                                weight=subset(Data, Country == "UK" & Quadrants99 == "Primer_and_Learner" &  Treatment_Group == "Control" & Sector == "Technology Sector")$cross_weight,weighty=subset(Data, Country == "UK" & Quadrants99 == "Primer_and_Learner" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$cross_weight,samedata=F)$additional[1]
uk_tech_scandal_se3 <- wtd.t.test(subset(Data, Country == "UK" & Quadrants99 == "Primer_and_Learner" &  Treatment_Group == "Control" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item, subset(Data, Country == "UK" & Quadrants99 == "Primer_and_Learner" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item,
                                  weight=subset(Data, Country == "UK" & Quadrants99 == "Primer_and_Learner" &  Treatment_Group == "Control" & Sector == "Technology Sector")$cross_weight,weighty=subset(Data, Country == "UK" & Quadrants99 == "Primer_and_Learner" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$cross_weight,samedata=F)$additional[4]

fr_tech_scandal3 <- -wtd.t.test(subset(Data, Country == "FR" & Quadrants99 == "Primer_and_Learner" &  Treatment_Group == "Control" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item, subset(Data, Country == "FR" & Quadrants99 == "Primer_and_Learner" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item,
                                weight=subset(Data, Country == "FR" & Quadrants99 == "Primer_and_Learner" &  Treatment_Group == "Control" & Sector == "Technology Sector")$cross_weight,weighty=subset(Data, Country == "FR" & Quadrants99 == "Primer_and_Learner" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$cross_weight,samedata=F)$additional[1]
fr_tech_scandal_se3 <- wtd.t.test(subset(Data, Country == "FR" & Quadrants99 == "Primer_and_Learner" &  Treatment_Group == "Control" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item, subset(Data, Country == "FR" & Quadrants99 == "Primer_and_Learner" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item,
                                  weight=subset(Data, Country == "FR" & Quadrants99 == "Primer_and_Learner" &  Treatment_Group == "Control" & Sector == "Technology Sector")$cross_weight,weighty=subset(Data, Country == "FR" & Quadrants99 == "Primer_and_Learner" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$cross_weight,samedata=F)$additional[4]

de_tech_scandal3 <- -wtd.t.test(subset(Data, Country == "DE" & Quadrants99 == "Primer_and_Learner" &  Treatment_Group == "Control" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item, subset(Data, Country == "DE" & Quadrants99 == "Primer_and_Learner" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item,
                                weight=subset(Data, Country == "DE" & Quadrants99 == "Primer_and_Learner" &  Treatment_Group == "Control" & Sector == "Technology Sector")$cross_weight,weighty=subset(Data, Country == "DE" & Quadrants99 == "Primer_and_Learner" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$cross_weight,samedata=F)$additional[1]
de_tech_scandal_se3 <- wtd.t.test(subset(Data, Country == "DE" & Quadrants99 == "Primer_and_Learner" &  Treatment_Group == "Control" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item, subset(Data, Country == "DE" & Quadrants99 == "Primer_and_Learner" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$tech_reg_score_factor_WaveB_4item,
                                  weight=subset(Data, Country == "DE" & Quadrants99 == "Primer_and_Learner" &  Treatment_Group == "Control" & Sector == "Technology Sector")$cross_weight,weighty=subset(Data, Country == "DE" & Quadrants99 == "Primer_and_Learner" &  Treatment_Group == "Tech - Scandal" & Sector == "Technology Sector")$cross_weight,samedata=F)$additional[4]

### Plotting the figure

par(mar=c(3.1,6.1,3.5,2.1))
plot(x=c(),y=c(),ylim=c(-0.4,0.7),xlim=c(0.54,1.1), ylab="Treatment Effect", main="", xaxt="n", xlab="",cex.lab=1.2)

points(0.58,us_tech_scandal1,pch=16, col = "black")
lines(x=c(0.58,0.58),y=c(us_tech_scandal1-1.68*us_tech_scandal_se1,us_tech_scandal1+1.68*us_tech_scandal_se1),lwd=2, col = "black")
points(0.60,us_tech_scandal2,pch=16, col = "red")
lines(x=c(0.60,0.60),y=c(us_tech_scandal2-1.68*us_tech_scandal_se2,us_tech_scandal2+1.68*us_tech_scandal_se2),lwd=2, col = "red")
points(0.62,us_tech_scandal3,pch=16, col = "blue")
lines(x=c(0.62,0.62),y=c(us_tech_scandal3-1.68*us_tech_scandal_se3,us_tech_scandal3+1.68*us_tech_scandal_se3),lwd=2, col = "blue")

points(0.72,uk_tech_scandal1,pch=16, col = "black")
lines(x=c(0.72,0.72),y=c(uk_tech_scandal1-1.68*uk_tech_scandal_se1,uk_tech_scandal1+1.68*uk_tech_scandal_se1),lwd=2, col = "black")
points(0.74,uk_tech_scandal2,pch=16, col = "red")
lines(x=c(0.74,0.74),y=c(uk_tech_scandal2-1.68*uk_tech_scandal_se2,uk_tech_scandal2+1.68*uk_tech_scandal_se2),lwd=2, col = "red")
points(0.76,uk_tech_scandal3,pch=16, col = "blue")
lines(x=c(0.76,0.76),y=c(uk_tech_scandal3-1.68*uk_tech_scandal_se3,uk_tech_scandal3+1.68*uk_tech_scandal_se3),lwd=2, col = "blue")

points(0.86,fr_tech_scandal1,pch=16, col = "black")
lines(x=c(0.86,0.86),y=c(fr_tech_scandal1-1.68*fr_tech_scandal_se1,fr_tech_scandal1+1.68*fr_tech_scandal_se1),lwd=2, col = "black")
points(0.88,fr_tech_scandal2,pch=16, col = "red")
lines(x=c(0.88,0.88),y=c(fr_tech_scandal2-1.68*fr_tech_scandal_se2,fr_tech_scandal2+1.68*fr_tech_scandal_se2),lwd=2, col = "red")
points(0.90,fr_tech_scandal3,pch=16, col = "blue")
lines(x=c(0.90,0.90),y=c(fr_tech_scandal3-1.68*fr_tech_scandal_se3,fr_tech_scandal3+1.68*fr_tech_scandal_se3),lwd=2, col = "blue")

points(1.00,de_tech_scandal1,pch=16, col = "black")
lines(x=c(1.00,1.00),y=c(de_tech_scandal1-1.68*de_tech_scandal_se1,de_tech_scandal1+1.68*de_tech_scandal_se1),lwd=2, col = "black")
points(1.02,de_tech_scandal2,pch=16, col = "red")
lines(x=c(1.02,1.02),y=c(de_tech_scandal2-1.68*de_tech_scandal_se2,de_tech_scandal2+1.68*de_tech_scandal_se2),lwd=2, col = "red")
points(1.04,de_tech_scandal3,pch=16, col = "blue")
lines(x=c(1.04,1.04),y=c(de_tech_scandal3-1.68*de_tech_scandal_se3,de_tech_scandal3+1.68*de_tech_scandal_se3),lwd=2, col = "blue")

legend("bottomleft", legend = paste(c("Uninformed", "Low Trust", "Low Trust & Uninformed")), col = c("black", "red", "blue"), y.intersp = 0.7,  pch = 19, bty = "n")

abline(h=0,lty="dashed")
axis(1, at=seq(0.61,1.06,by=0.14), labels = FALSE)
text(seq(0.61,1.06,by=0.14), par("usr")[3] - 0.03, labels = c("US", "UK", "FR", "DE"), srt = 0, pos = 1, xpd = TRUE,cex=0.8)




#######################
#### Online Appendix K – Robustness Check on Populism and Treatment Effect
#######################

# Filter data to include only relevant groups
Combo_filtered2 <- Data %>%
  mutate(elite_group = ifelse(elite_dom_1 > 4, "Above 3", "3 or Below")) %>%
  filter(!is.na(elite_group))   

# Run separate regressions by elite group
model_results2 <- Combo_filtered2 %>%
  group_by(elite_group) %>%
  do(tidy(lm(tech_reg_score_factor_WaveB_4item ~ Treatment_Group, data = .),
          conf.int = TRUE, conf.level = 0.90))

# Keep only the Treatment_Group coefficient
plot_data2 <- model_results2 %>%
  filter(term == "Treatment_GroupTech - Scandal") %>%  # matches your factor name
  select(elite_group, estimate, conf.low, conf.high)

# Relabel before plotting
plot_data2 <- plot_data2 %>%
  mutate(elite_group = recode(elite_group,
                              "Above 3" = "Believes that the \nEconomy is Rigged",
                              "3 or Below" = "Does Not Believe that the \nEconomy is Rigged"))

# Create the plot
ggplot(plot_data2, aes(x = elite_group, y = estimate)) +
  geom_point(size = 3, color = "black") +
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high),
                width = 0.15, color = "black") +
  geom_hline(yintercept = 0, linetype = "dashed", color = "gray50") +
  labs(
    title = "",
    x = "",
    y = "Treatment Effect"
  ) +
  theme_classic(base_size = 13) +
  scale_y_continuous(limits = c(-0.10, 0.50)) +   
  coord_flip()  
